package com.ahwei.controller;

import com.ahwei.context.AppContext;
import com.ahwei.pojo.User;
import com.ahwei.pojo.UserDetail;
import com.ahwei.pojo.enums.Result;
import com.ahwei.pojo.model.PageResult;
import com.ahwei.service.UserService;
import com.ahwei.service.impl.UserServiceImpl;
import com.ahwei.util.DateUtils;
import com.ahwei.util.FileUtils;
import com.ahwei.util.LogUtils;
import com.ahwei.util.StringUtils;
import com.ahwei.util.anno.Controller;
import com.ahwei.util.anno.FunctionMapping;
import com.ahwei.util.anno.RequestMapping;
import com.ahwei.web.filter.AntiStealingLinkFilter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author：ahwei163@qq.com
 *
 * @date: 202*-03-15 15:37:49
 * @description: 这是一个Java文件！
 */
@Controller
public class UserController {
    @FunctionMapping("注册验证")
    @RequestMapping("/registerCheck")
    public String registerCheck(String account){
        return "ajax:"+ (userService().findUserByAccount(account) == null);
    }

    @FunctionMapping("注册")
    @RequestMapping("/userRegister")
    public String userRegister(String account,String password){
        UserDetail userDetail = new UserDetail(0L,account,"保密",new Date(),"未知","user.jpg");
        User user = new User(0L,account,password,AppContext.ROLE_STUDENT,userDetail,null);

        //进行注册
        Result result = userService().userRegister(user);
        if (result == Result.REGISTER_SUCCESS){
            //注册成功
            return "msg:"+"<script>alert('"+result.getMsg()+"');window.location.href='login.html';</script>";
        }else if (result == Result.REGISTER_FAIL){
            return "msg:"+"<script>alert('"+result.getMsg()+"');window.location.href='register.html';</script>";
        }else{
            return "msg:"+"<script>alert('"+result.getMsg()+"');window.location.href='register.html';</script>";
        }
    }

    @FunctionMapping("退出登录")
    @RequestMapping("/userExit")
    public String userExit(HttpServletResponse response, HttpSession session){
        //获取用户
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser != null) {
            Cookie cookie = new Cookie("account", currentUser.getAccount());
            cookie.setMaxAge(0);
            response.addCookie(cookie);

            session.removeAttribute("currentUser");
        }
        return "redirect:showIndex";
    }

    @FunctionMapping("登录")
    @RequestMapping("/userLogin")
    public String userLogin(String account, String password,HttpSession session, HttpServletResponse response,PrintWriter out) throws IOException {
        //获取登录结果
        Result result = userService().UserLogin(account, password);

        if (result == Result.LOGIN_SUCCESS){
            //添加cookie
            Cookie cookie = new Cookie("account", account);
            cookie.setMaxAge(24*60*60);
            //cookie.setMaxAge(3*24*60*60);
            response.addCookie(cookie);
            //获取用户信息
            User user = userService().findUserByAccount(cookie.getValue());

            //将用户保存到session
            session.setAttribute("currentUser", user);
            return "redirect:showIndex";
        }else if (result == Result.USER_DOES_NOT_EXIST){
            //用户不存在
            return "msg:"+"<script>alert('"+result.getMsg()+"');window.location.href='login.html';</script>";
        }else if (result == Result.ACCOUNT_PROHIBIT_USE){
            //账号被禁用
            return "msg:"+"<script>alert('"+result.getMsg()+"');window.location.href='login.html';</script>";
        }else{
            return "msg:"+"<script>alert('"+result.getMsg()+"');window.location.href='login.html';</script>";
        }
    }
    @FunctionMapping("修改用户基本信息")
    @RequestMapping("/updateUser")
    public String updateUser(long uid,Integer roleId){
        int i = userService().updateUser(new User(uid, "", "", roleId, null, null));
        return i > 0 ? "ajax:true":"ajax:false";
    }

    @FunctionMapping("获取当前用户")
    @RequestMapping("/getCurrentUser")
    public User getCurrentUser(HttpSession session){
        User currentUser = (User)session.getAttribute("currentUser");
        Long uid = currentUser.getUid();

        UserService userService = userService();
        User userByUid = userService.findUserByUid(uid);

        //将用户新信息保存到session
        session.removeAttribute("currentUser");
        session.setAttribute("currentUser", userByUid);
        return userByUid;
    }

    @FunctionMapping("获取所有用户")
    @RequestMapping("/getAllUser")
    public PageResult<User> getAllUser(String account,String name,String sex,Integer pageNo,HttpSession session){
        return userService().findAllUser(account, name, sex, pageNo);
    }

    @FunctionMapping("根据关键字查询用户字段")
    @RequestMapping("/queryUserInfoColumnByKeyword")
    public List<String> queryUserInfoColumnByKeyword(String column,String keyword){
        return userService().queryUserInfoColumnByKeyword(column, keyword);
    }

    @FunctionMapping("修改用户信息")
    @RequestMapping("/userInfoUpdate")
    public String userInfoUpdate(long uid, String editType, String newText, HttpServletRequest request ,HttpSession session) throws IOException, ServletException {
        //获取用户详情
        UserDetail userDetail = userService().findUserDetailByUid(uid);
        if (userDetail == null) userDetail = new UserDetail(uid,"未填写","保密",new Date(),"未知","user.jpg");
        switch (editType){
            case "headPicUrl":
                Map<String, String> map = FileUtils.fileUpload(request);
                //获取上传的文件名
                String headPicUrl = map.get("EditHeadPic");
                LogUtils.info("headPicUrl = " + headPicUrl);
                userDetail.setHeadPicUrl(headPicUrl);
                break;
            case "name":
                userDetail.setName(newText);
                break;
            case "sex":
                userDetail.setSex(newText);
                break;
            case "birthday":
                userDetail.setBirthday(DateUtils.stringDate(newText));
                break;
            case "address":
                userDetail.setAddress(newText);
                break;
            default:
                throw new RuntimeException("非法请求！！!");
        }
        //执行修改
        Result result = userService().updateUserDetail(userDetail);


        // String requestURL = request.getRequestURL().toString().replace(request.getServletPath(),"");

        // String referer = request.getHeader("referer").replace(requestURL,"");
        //如果来自用户管理界面的修改，就转发到queryUserPageServlet
        /*if ("adminpages/userManagerPages.jsp".equals(referer)){
            int pageNo = (int)request.getSession().getAttribute("pageNo");
            //request.getRequestDispatcher("queryUserPageServlet?pageNo="+pageNo).forward(request,response);
            return "";
        }*/
        //设置用户新信息  代码到这说明是用户修改自己信息
        User currentUser = userService().findUserByUid(uid);
        session.removeAttribute("currentUser");
        session.setAttribute("currentUser",currentUser);

        return "msg: success";
    }

    private UserService userService(){
        return new UserServiceImpl();
    }
}
